package com.imooc.oauth2.server.config;

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.imooc.commons.constant.ApiConstant;
import com.imooc.commons.model.domain.ResultInfo;
import com.imooc.commons.utils.ResultInfoUtil;

import io.micrometer.core.instrument.util.StringUtils;

/**
 * \* @author: bear
 * \* Date: 2021-07-11-17:24
 * \* describe:
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

	@Resource
	private ObjectMapper objectMapper;

	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response,
			AuthenticationException authException) throws IOException {
		// 返回 JSON
		response.setContentType("application/json;charset=utf-8");
		// 状态码 401
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		// 写出
		PrintWriter out = response.getWriter();
		String errorMessage = authException.getMessage();
		if (StringUtils.isBlank(errorMessage)) {
			errorMessage = "登录失效!";
		}
		ResultInfo result = ResultInfoUtil.buildError(ApiConstant.ERROR_CODE,
				errorMessage, request.getRequestURI());
		out.write(objectMapper.writeValueAsString(result));
		out.flush();
		out.close();
	}
}
